﻿using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

namespace NewSolution
{
    public class Program
    {
        static async Task Main(string[] args)
        {
            string filePathA = "inputa.bin";
            string filePathB = "inputd.bin";

            int bufferSize = 15;
            byte[] pattern = { 0x01, 0x02, 0x03, 0x04 };

            // 文件读取模块
            var fileReadBlockA = new FileReadBlock(filePathA, bufferSize);
            var fileReadBlockB = new FileReadBlock(filePathB, bufferSize);

            // 分割模块
            var segmentBlockA = new SegmentBlock(pattern, bufferSize).CreateTransformBlock();
            var segmentBlockB = new SegmentBlock(pattern, bufferSize).CreateTransformBlock();

            // 整合模块
            var integrateBlockA = new IntegrateBlock().CreateTransformBlock();
            var integrateBlockB = new IntegrateBlock().CreateTransformBlock();

            // 使用JoinBlock来组合两个整合后的帧
            var joinBlock = new JoinBlock<(byte[], int), (byte[], int)>();

            // 比较模块
            var compareBlock = new CompareBlock().CreateTransformBlock();
           

            // 输出模块
            var consoleBlock = new ConsoleBlock().CreateActionBlock();

            // 连接模块
            fileReadBlockA.ReadBytes().ToList().ForEach(buffer => segmentBlockA.Post(buffer));
            fileReadBlockB.ReadBytes().ToList().ForEach(buffer => segmentBlockB.Post(buffer));

            segmentBlockA.LinkTo(integrateBlockA, new DataflowLinkOptions { PropagateCompletion = true });
            segmentBlockB.LinkTo(integrateBlockB, new DataflowLinkOptions { PropagateCompletion = true });

            integrateBlockA.LinkTo(joinBlock.Target1, new DataflowLinkOptions { PropagateCompletion = true });
            integrateBlockB.LinkTo(joinBlock.Target2, new DataflowLinkOptions { PropagateCompletion = true });

            joinBlock.LinkTo(compareBlock, new DataflowLinkOptions { PropagateCompletion = true });

            compareBlock.LinkTo(consoleBlock, new DataflowLinkOptions { PropagateCompletion = true });

            // 等待所有块完成
            await Task.WhenAll(
                segmentBlockA.Completion,
                segmentBlockB.Completion,
                integrateBlockA.Completion,
                integrateBlockB.Completion,
                compareBlock.Completion,
                consoleBlock.Completion
            );
        }
    }
}